<?php
namespace control;
/*
*费用申请类
*/

class feeApplyClass extends adIndexClass
{

    private const page = 'feeApply';
    private const table = 'cost';
    private const title = '费用申请';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('feeApply.home.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'  => [
                        'name'  => L('feeApply.home.stid'),
                        'width' => 200,
                    ],
                    'deptName'         => [
                        'name'  => L('feeApply.home.deptName'),
                        'width' => 200,
                    ],
                    'reason'          => [
                        'name'  => L('feeApply.home.reason'),
                        'width' => 300,
                    ],
                    'money'          => [
                        'name'  => L('feeApply.home.money').'(' . static::$unit . ')',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => L('feeApply.home.createTime'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('feeApply.home.state'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('feeApply.home.orderNo') => text(array("name" => "orderNo")),
                    L('feeApply.home.deptName')   => text(array("name" => "deptName")),
                    L('feeApply.home.reason') => text(array("name" => "reason")),
                ],
                [
                    L('feeApply.home.stid')  =>  selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('feeApply.home.state') => select(array("name" => "state", "option" => $this->stateOption)),
                    L('feeApply.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>".L('feeApply.homeSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('feeApply.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//编号
            "reason" => $this->post('reason'),//事由
            "deptName" => $this->post('deptName'),//申请人部门
        );
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//申请人
            "state" => $this->post('state'),//状态
            "classify" => 1,
            'coid' => self::$coid
        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('feeApply.homeSearch.detail'), "click" => "newIframe('" . L('feeApply.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('feeApply.edit.money')."：" => text(["name" => "money", 'class' => 'text', "value" => $info['money']]),
                    must . L('feeApply.edit.bankNum')."：" => text(["name" => "bankNum", 'class' => 'text', "value" => $info['bankNum']]),
                ],
                [
                    must . L('feeApply.edit.reason')."：" => textarea(["name" => "reason", 'class' => 'textarea', "value" => $info['reason']]),

                ],
                [
                    L('feeApply.edit.text')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?:$id]),
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 300, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'reason' => $this->post('reason'),
            'money' => $this->post('money'),
            'bankNum' => $this->post('bankNum'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'reason' => L('feeApply.edit.reason'),
            'money' => L('feeApply.edit.money'),
            'bankNum' => L('feeApply.edit.bankNum'),
        ];
        $rules = [
            'reason' => 'required',
            'money' => 'required|numeric',
            'bankNum' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('feeApply.editEdit.power');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'FYSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => $id,
                    'classify' => 1,
                    'coid' => self::$coid,
                    'deptName' => $department['name'],
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('feeApply.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => L('salesContract.auditButton.start'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '费用申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('salesContract.auditButton.addApprover'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.transfer'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.approval'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('salesContract.auditButton.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('feeApply.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => L('feeApply.detail.detail'),
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('feeApply.detail.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];

            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿'){
                //按钮
                $button[] = [
                    "name" => L('feeApply.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            $audit = query('audit', " targetId = '$info[id]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        L('feeApply.detail.reason') => $info['reason'],
                        L('feeApply.detail.money')."(" . static::$unit . ")" => $info['money'],
                        L('feeApply.detail.bankNum') => $info['bankNum'],
                    ),
                    array(
                        L('feeApply.detail.text') => pre($info['text']),
                    ),
                ),
                L('feeApply.detail.sys') => array(
                    array(
                        L('feeApply.detail.orderNo') => $info['orderNo'],
                        L('feeApply.detail.deptName') => $info['deptName'],
                        L('feeApply.detail.stid') => self::findStaff($info['stid']),
                        L('feeApply.detail.time') => $info['time'],
                    ),
                    array(
                        L('feeApply.detail.commitTime') => self::null($audit['commitTime']),
                        L('feeApply.detail.state') => $info['state'],
                    ),
                ),
                L('feeApply.detail.process') => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),

            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('feeApply.operate.msg');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('feeApply.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('feeApply.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('feeApply.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('feeApply.delete.fail');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('feeApply.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('feeApply.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('feeApply.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('feeApply.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

